package com.itheima.advice;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;


public class TxManager {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    PlatformTransactionManager transactionManager = null;
    TransactionDefinition transactionDefinition = null;
    TransactionStatus transactionStatus = null;

    //写事务语句

    //之前先开始事务，创建对象
    public void before(){
        //创建事务管理器对象，并注入数据源对象
        transactionManager = new DataSourceTransactionManager(dataSource);
        //创建事务定义对象
        transactionDefinition = new DefaultTransactionDefinition();
        //开始事务
        //事务的状态
        transactionStatus = transactionManager.getTransaction(transactionDefinition);
    }

    //后值对象，运行完成后提交事务
    public void afterReturning(){
        //提交事务
        transactionManager.commit(transactionStatus);
    }
    //出现异常对象，出现异常后回滚事务
    public void afterThrowing(){
        transactionManager.rollback(transactionStatus);

    }

}
